package com.caiyi.financial.nirvana.sms.gateway;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.entity.SmsAccountBlacklist;
import com.caiyi.financial.nirvana.sms.entity.SmsGateway;
import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.MessageActionEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsAccountBlacklistSourceEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 默认网关处理程序
 */
public class DefaultGateWay implements GateWay {

    private static final Logger logger = LoggerFactory.getLogger(DefaultGateWay.class);

    public final Map<String, String> S2M = new ConcurrentHashMap();

    public SmsGateway info;

    public ChannelHandlerContext context;

    public int idleNotifyTime = 60;

    // 是否登录
    public boolean login = false;

    // 初始化
    @Override
    public void init(SmsGateway info) {
        this.info = info;
    }

    @Override
    public void start() throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void doConnect() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void connectSuccess(ChannelHandlerContext context) {
        logger.info("通道【{}】连接成功", info.getName());
        this.context = context;
    }

    @Override
    public void loginSuccess() {
        logger.info("通道【{}】登录成功", info.getName());
        this.login = true;
    }

    @Override
    public void loginFail(int status, String message) {
        logger.info("通道【{}】登录失败，失败代码：{}", info.getName(), message);
        this.login = false;
    }

    @Override
    public void sendMessage(SendQueueEntity entity) {
    }

    @Override
    public void terminating() {
        logger.info("通道【{}】正在关闭", info.getName());
    }

    @Override
    public void terminated() {
        logger.info("通道【{}】已经关闭", info.getName());
        this.login = false;
        close();
    }

    @Override
    public void onSubmitResponse(int status, String messageId, String remoteMsgId) {
        SendQueueEntity entity = new SendQueueEntity();
        entity.setSendTime(new Date());
        entity.setStatus(status);
        entity.setMessageId(messageId);
        entity.setResult(remoteMsgId);
        entity.setAction(MessageActionEnum.RESPONSE.index);
        JedisService.lpush(JedisKey.SMS_QUEUE_MSG_DB, JSON.toJSONString(entity));
    }

    // 收到上行短信
    @Override
    public void receiveMessage(SmsReceiveMessage message) {
        String content = message.getContent();
        if(StringUtils.isBlank(message.getAccessNumber())){
            logger.error("DefaultGateWay receiveMessage message {}",message);
            return;
        }
        if (StringUtils.isNotBlank(content) && StringUtils.isNotBlank(message.getAccount())) {
            content = content.trim();
            if (content.equalsIgnoreCase("td")) {
                SmsAccountBlacklist accountBlack = new SmsAccountBlacklist();
                accountBlack.setAccount(message.getAccount());
                accountBlack.setPhone(message.getPhone());
                accountBlack.setSource(SmsAccountBlacklistSourceEnum.TD.index);
                String blackStr = JSON.toJSONString(accountBlack);
                logger.info("receiveMessage black str : {}", blackStr);
                JedisService.lpush(JedisKey.SMS_QUEUE_BLACKLIST_INSERT_DB, blackStr);
            }
        }
        message.setContent(content);
        String msgStr = JSON.toJSONString(message);
        JedisService.lpush(JedisKey.SMS_QUEUE_RECEIVE_MESSAGE_DB, msgStr);
    }

    // 收到状态报告
    @Override
    public void receiveReport(int status, String messageId, String result) {
        if (StringUtils.isBlank(messageId)) {
            return;
        }
        SendQueueEntity entity = new SendQueueEntity();
        entity.setReceiveTime(new Date());
        entity.setStatus(status);
        entity.setMessageId(messageId);
        entity.setResult(result);
        entity.setAction(MessageActionEnum.CALLBACK.index);
        JedisService.lpush(JedisKey.SMS_QUEUE_MSG_DB, JSON.toJSONString(entity));
    }

    @Override
    public void close() {
    }

    public boolean notifyStatus(NotifyQueueEntity entity) {
        return false;
    }

    //主动查询获取报告状态
    public boolean queryStatus() throws Exception {
        throw new NoSuchMethodException("未实现此方法");
    }

    //主动获取上行信息
    public boolean queryReceiveMsg() throws Exception {
        throw new NoSuchMethodException("未实现此方法");
    }

    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return false;
    }

    public int queryBalance() throws Exception {
        throw new NoSuchMethodException("未实现此方法");
    }

}
